package com.dal.drools_service.service;

import com.dal.drools_service.entity.City;
import com.dal.drools_service.entity.Custom;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.mvel2.templates.TemplateRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;

@Service
@Slf4j
public class RuleService {
    @Autowired
    private KieBase kieBase;


    @Value("${rule.expiration-date}")
    private String expirationDate;
    @Value("${rule.effective-date}")
    private String effectiveDate;
    private String loadFile(String fileName) throws IOException {
        return new String(getClass().getClassLoader().getResourceAsStream(fileName).readAllBytes(), StandardCharsets.UTF_8);
    }
    public Custom executeRule(Custom custom, City city) throws ParseException {
        KieSession kieSession = kieBase.newKieSession();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date expirationDate = sdf.parse(this.expirationDate);
        log.info("expirationDate {}",expirationDate);
        Date effectiveDate = sdf.parse(this.effectiveDate);
        //插入事实对象
        kieSession.insert(effectiveDate);
        kieSession.insert(expirationDate);
//        kieSession.setGlobal("effectiveDate", effectiveDate);
//        kieSession.setGlobal("expirationDate", expirationDate);
        kieSession.insert(custom);
        kieSession.insert(city);
        kieSession.fireAllRules();
        kieSession.dispose();

        return custom;
    }
}
